﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;

using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;

namespace 代码编辑控件
{
    public partial class MainWindow : Window
    {
        private readonly NewFoldingStrategy _foldingStrategy;
        private readonly FoldingManager _foldingManager;

        private SimpleJsonParser parser = new SimpleJsonParser(null);

        public MainWindow()
        {
            InitializeComponent();

            // 初始化折叠管理器
            // _foldingManager = FoldingManager.Install(textEditor.TextArea);
            // 初始化折叠策略
            // _foldingStrategy = new NewFoldingStrategy();
            // UpdateFoldings(_foldingStrategy, textEditor.Document);
            // var options = new JsonSerializerOptions { WriteIndented = true };

            // 设置 JSON 语法高亮
            // textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("JavaScript");
            // 监听文档变化，更新折叠
            // textEditor.Document.Changed += Document_Changed;

            this.Loaded += MainWindow_Loaded;
        }

        private void Document_Changed(object sender, DocumentChangeEventArgs e)
        {
            UpdateFoldings(_foldingStrategy, textEditor.Document);
        }

        private void UpdateFoldings(NewFoldingStrategy strategy, TextDocument document)
        {
            var foldings = strategy.GetFoldings(document);
            _foldingManager.UpdateFoldings(foldings, document.TextLength);
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // this.textEditor.Opacity = 0.4;
            // 示例 JSON 字符串
            // string json = "{" + " \"appName\": \"EcoPaste\", \"appVersion\": \"0.1.0\", \"tauriVersion\": \"1.7.2\", \"platform\": \"Windows_NT\", \"platformArch\": \"x86_64\", \"platformVersion\": \"10.0.22631\" " + "}";

            // 创建解析器实例并解析 JSON
            // var result = parser.Parse(); // 执行解析

            // 执行解析

            // Debug.WriteLine($"Parsed JSON:{result.Count}");
            // this.textEditor.Text = $"Parsed JSON:{result}";

            // 将结果强制转换为 Dictionary<string, object>
            // var resultDict = (Dictionary<string, object>)result;

            // 打印解析结果
            // PrintDictionary((Dictionary<string, object>)result);

            // Debug.WriteLine(((Dictionary<string, object>)result).Keys);
            // Debug.WriteLine(string.Join(", ", resultDict.Values));


            // 输出解析结果
        }


        // 打印字典的内容
        private void PrintDictionary(Dictionary<string, object> dictionary)
        {
            foreach (var kvp in dictionary)
            {
                Debug.WriteLine($"{kvp.Key}: {FormatValue(kvp.Value)}");
                // this.textEditor.Text += $"\n{kvp.Key}: {FormatValue(kvp.Value)}";
            }
        }

        // 格式化值的显示
        private static string FormatValue(object value)
        {
            if (value is string)
                return $"\"{value}\""; // 字符串加上引号
            else if (value is Dictionary<string, object> dict)
            {
                return "{" + string.Join(", ", dict.Select(kvp => $"{kvp.Key}: {FormatValue(kvp.Value)}")) + "}";
            }
            else if (value is List<object> list)
            {
                return "[" + string.Join(", ", list.Select(FormatValue)) + "]";
            }
            return value.ToString(); // 其他类型直接转换为字符串
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // this.parser = new SimpleJsonParser(this.textEditor.Text);
            ;
            var result = parser.OutJsonData(new SimpleJsonParser(this.textEditor.Text).Parse());
            this.Jx.Text = string.Empty;
            this.Jx.Text = "解析总量：" + result.Count.ToString();
            foreach (var item in result)
            {
                this.Jx.Text += "\n" + item.Key + ":" + item.Value;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.textEditor.Text = SimpleJsonParser.FormatJson(this.textEditor.Text);
        }
    }

    public class NewFoldingStrategy
    {
        public IEnumerable<NewFolding> GetFoldings(TextDocument document)
        {
            List<NewFolding> foldings = new List<NewFolding>();

            // 示例：折叠大括号之间的内容
            for (int i = 0; i < document.TextLength; i++)
            {
                if (document.GetText(i, 1) == "{")
                {
                    int startOffset = i + 1;
                    int endOffset = FindMatchingBracket(document, i);

                    if (endOffset != -1)
                    {
                        foldings.Add(new NewFolding(startOffset, endOffset - startOffset));
                    }
                }
            }

            return foldings;
        }

        private int FindMatchingBracket(TextDocument document, int startOffset)
        {
            int bracketCount = 1;
            for (int i = startOffset + 1; i < document.TextLength; i++)
            {
                char c = document.GetText(i, 1)[0];
                if (c == '{')
                {
                    bracketCount++;
                }
                else if (c == '}')
                {
                    bracketCount--;
                    if (bracketCount == 0)
                    {
                        return i;
                    }
                }
            }
            return -1;
        }
    }

}
